import { useNotificationStore } from './notificationStore'
import { ApiEndpoints } from '~/types/ApiEndpoints'

interface IState {
  user: {
    birthDate: null | string
    cityEn: null | string
    cityRu: null | string
    email: null | string
    firstNameEn: null | string
    firstNameRu: null | string
    head1Id: null | string
    head1NameEn: null | string
    head1NameRu: null | string
    head1Email: null | string
    id: string
    lastNameEn: null | string
    lastNameRu: null | string
    orgNameEn: null | string
    orgNameRu: null | string
    phone: null | string
    positionNameEn: null | string
    positionNameRu: null | string
    unitNameEn: null | string
    unitNameRu: null | string
    workplace: null | string
    favorites: string[]
    unitId: string | null
    hideEmployee: boolean
    orgUuid: string | null
    positionId: string | null
  }
  pendingOrNeedFetchUserInfo: boolean
}

const initialState: IState['user'] = {
  birthDate: null,
  cityEn: null,
  cityRu: null,
  email: null,
  firstNameEn: null,
  firstNameRu: null,
  head1Id: null,
  head1NameEn: null,
  head1NameRu: null,
  head1Email: null,
  id: '',
  lastNameEn: null,
  lastNameRu: null,
  orgNameEn: null,
  orgNameRu: null,
  phone: null,
  positionNameEn: null,
  positionNameRu: null,
  unitNameEn: null,
  unitNameRu: null,
  workplace: null,
  favorites: [],
  unitId: null,
  hideEmployee: false,
  orgUuid: null,
  positionId: null
}

export const useUserStore = defineStore('userStore', {
  state: () =>
    ({
      user: { ...initialState },
      pendingOrNeedFetchUserInfo: true
    } as IState),
  actions: {
    async getMe() {
      this.pendingOrNeedFetchUserInfo = true
      const { data } = await useAPIFetch(ApiEndpoints.ME)
      this.user = useUnProxy(data) as IState['user']
      this.pendingOrNeedFetchUserInfo = false
    },
    changeFavorites(id: string) {
      const notificationStore = useNotificationStore()
      if (this.user.favorites.includes(id)) {
        this.user.favorites = this.user.favorites.filter(
          (favId) => favId !== id
        )
        notificationStore.showNotification('Контакт удален из избранных')
      } else {
        this.user.favorites.push(id)
        notificationStore.showNotification('Контакт добавлен в избранные')
      }
    }
  },
  getters: {
    getIsFavorite: (state) => {
      return (id: string) => state.user.favorites.includes(id)
    }
  }
})
